package com.chap7;

import java.util.concurrent.locks.AbstractQueuedSynchronizer;

/**
 * Created by IntelliJ IDEA.
 * User: bj910
 * Date:2023-03-21
 * Time: 5:34
 * To change this template use File | Settings | File Templates.
 */
//作业：自己实现可重入功能
public class MyLock extends AbstractQueuedSynchronizer {
    //自己实现的时候，已经有造好的轮子，可以在此基础上扩展，没必要重新定义
    @Override
    protected boolean tryAcquire(int unused) {
        final Thread current = Thread.currentThread();
        int c = getState();
        if (c == 0) {
            if (compareAndSetState(0, unused)) {
                setExclusiveOwnerThread(current);
                return true;
            }
        }
        else if (current == getExclusiveOwnerThread()) {
            int nextc = c + unused;
            if (nextc < 0) // overflow
                throw new Error("Maximum lock count exceeded");
            setState(nextc);
            return true;
        }
        return false;
    }

    @Override
    protected boolean tryRelease(int releases) {
        int c = getState() - releases;
        if (Thread.currentThread() != getExclusiveOwnerThread())
            throw new IllegalMonitorStateException();
        boolean free = false;
        if (c == 0) {
            free = true;
            setExclusiveOwnerThread(null);
        }
        setState(c);
        return free;
    }
    //基于aqs实现 不用考虑：竞争锁失败的线程入队出队、等待对象唤醒等等操作
    public void lock(){
        acquire(1);
    }

    public boolean tryLock(){
        return tryAcquire(1);
    }

    public void unLock(){
        release(1);
    }
    public boolean isLocked(){
        return isHeldExclusively();
    }
}
